<template>
    <div class="Table">
        <div id="left-draw" class="left-draw" ref="rightCAD1"></div>
    </div>
</template>

<script>
import $ from "jquery";
import {
    getSvgByFun,
    getPartsMark,
    getVisualMark,
    GetExThickInspPaperMarker,
    getThickDeterResReportBalloonData,
} from "@/api/api";
import { getLocalStorage } from "@/utils/storage";
import eventBus from "@/eventBus/bus";
import _ from 'lodash-es';
import { showLoading, hideLoading } from "@/utils/loading";
import * as svg_opt from "@/utils/svg_opt.js";
export default {
    name: "DeviceLoginIndex",
    data() {
        return {

            MapList: [],
            MapValue: 8,
            pfdData: [],
            inSourceUrl: '',
            inSourceUrl1: '',
            isSourcePic: false,

            activeMackUp: null,

            FunType: 1,
            tar: '',
            NoData: false

        };
    },
    components: {
    },
    props: [],// 1列表2列表-图形
    watch: {

    },
    methods: {
        TestFn() {
            this.getFullFieldMapListApi();
        },



        // 右侧图形逻辑
        // 获取右侧下拉框
        // async getFullFieldMapListApi() {
        //     console.log('123');
        //     let dataJson = {};
        //     let res = await getFullFieldMapList(dataJson)
        //     this.MapList = [];
        //     if (res.data.code != 0) {
        //         return;
        //     }
        //     this.MapList = res.data.data;
        //     this.MapValue = this.MapList[0].areaCode;
        //     // svg图处理
        //     this.svgStartFn(this.MapList[0].areaFile);
        //     this.getFullFieldMarkApi(this.MapList[0].areaCode);

        // },
        // async MapValueChange(value) {
        //     let areaFile = this.MapList.filter(item => item.areaCode == value)[0].areaFile || '';
        //     console.log('areaFile', areaFile);
        //     // areaFile = 'http://192.168.33.89:8085\\aaa\\pfd\\web\\PFD.svg';
        //     this.svgStartFn(areaFile);
        //     this.getFullFieldMarkApi(value);

        //     this.getPfdByPlantApi(value);

        //     this.activeMackUp = null;
        // },

        // 获取图纸
        // 功能类型 1=設備図面 2=設備仕様（図面） 3=肉厚測定結果（図面） 4=目視/非破壊検査計画 5=肉厚測定計画
        async getSvgByFunFn(PltCode, DmgCode, FunType, macNumb, Data) {
            this.NoData = false;

            try {
                svg_opt.removeSvg();

            } catch (error) {

            }
            let dataJson = {
                PltCode,
                DmgCode,
                FunType
            };
            let res = await getSvgByFun(dataJson)
            if (res.data.code != 0) {
                // 绘制线组
                this.NoData = true;
                setTimeout(() => {
                    this.$emit('changeWait', true); // 通知上层加载完毕
                }, 500);
                return;
            }
            this.svgStartFn(res.data.data[0].sourcePath, PltCode, DmgCode, FunType, macNumb, Data, res.data.data[0].ext);
            //     this.getFullFieldMarkApi(this.MapList[0].areaCode);
        },

        // svg开始处理入口
        svgStartFn(inSourceUrl, PltCode, DmgCode, FunType, macNumb, dataJson, originExt) {
            showLoading();
            if (inSourceUrl == null || typeof inSourceUrl == "undefined") {
                svg_opt.removeSvg();
                return;
            }
            let num = inSourceUrl.lastIndexOf(".") + 1;
            this.sourceExt = inSourceUrl.substring(num);
            this.inSourceUrl = inSourceUrl;
            this.inSourceUrl1 = inSourceUrl;
            this.isSourcePic = false;


            if (
                this.sourceExt == "png" ||
                this.sourceExt == "jpg" ||
                this.sourceExt == "gif" ||
                this.sourceExt == "bmp" ||
                this.sourceExt == "jpeg" ||
                this.sourceExt == "tif" ||
                this.sourceExt == "tiff"
            ) {
                this.isSourcePic = true;
                this.inSourceUrl = require("@/assets/model/method-draw-image.svg");
            } else {
                this.isSourcePic = false;
                this.inSourceUrl = inSourceUrl;
            }
            console.log('this.isSourcePic', this.sourceExt, this.inSourceUrl, this.isSourcePic);
            if (!this.inSourceUrl || this.inSourceUrl == "") {
                svg_opt.removeSvg();
                $('.left-draw').html('NO Data');
                $('.left-draw').css({
                    'display': 'flex',
                    'align-items': 'center',
                    'justify-content': 'space-evenly',
                    'font-size': '15px'
                });
                return;
            } else {
                // fetch(this.svgSourceUrl)
                //     .then(async response => {
                //         // 处理响应的数据
                //         if (response.status != 200) {
                //             svg_opt.removeSvg();
                //             $('.left-draw').html('NO Data');
                //             $('.left-draw').css({
                //                 'display': 'flex',
                //                 'align-items': 'center',
                //                 'justify-content': 'space-evenly',
                //                 'font-size': '15px'
                //             });
                //             return
                //         }
                //         window.open(this.currentItem.path);
                //     })
                //     .catch(async error => {
                //     });
            }



            this.isSvgLoading = true;
            svg_opt.setSvgLineWidthRatio(1.5);
            svg_opt.setSvgBoundingBoxRatio(0, 0, 1);
            svg_opt.setCanClickSelectMarkup(true);

            svg_opt.setCanEditSelectMarkup(false);
            svg_opt.setCanFitPositionAndScale(false);
            svg_opt.setEditDotWidthRatio(3);
            hideLoading();
            console.log('this.inSourceUrl', this.inSourceUrl);
            svg_opt.AddSvg(this.inSourceUrl, "left-draw", this.onSvgMousePosChange, true,
                    0,
                    0,
                    originExt == "wmf" ? 1 : -1);
            svg_opt.SetSvgMouseMode(0);
            svg_opt.setLoadCallBack(this.onSvgLoaded);
            svg_opt.setSelectCallBack(this.onLineGroupSelect);
            console.log(this.inSourceUrl);
            this.getFullFieldMarkApi(PltCode, DmgCode, FunType, macNumb, dataJson);
        },
        // svg加载失败处理
        onSvgLoaded(error) {
            console.log("onSvgLoaded --- ", error);
            this.isSvgLoading = false;
            hideLoading();
            if (error) {
                console.log(error);
                return;
            }

            this.isSvgLoaded = true;

            if (this.isSourcePic) {
                console.log("onSvgLoaded --- ", 3123123, this.inSourceUrl1);

                svg_opt.changeSvgElementData({
                    tagName: "img-content",
                    paramName: "xlink:href",
                    newValue: this.inSourceUrl1,
                    isReport: true
                });
            }
        },
        // 获取MarkUp数据
        async getFullFieldMarkApi(PltCode, DmgCode, FunType, macNumb, Data) {
            showLoading()
            let dataJson = {
                DmgCode,
                blnKbn: 1,
                macNumb,
                PltCode
            };
            let Api = getPartsMark;
            //  部品
            // 功能类型 1=設備図面 2=設備仕様（図面） 3=肉厚測定結果（図面） 4=目視/非破壊検査計画 5=肉厚測定計画
            if (FunType == 1 || FunType == 2) {
                Api = getPartsMark;
            } else if (FunType == 3) {
                Api = getThickDeterResReportBalloonData;
                dataJson = Data;
            } if (FunType == 4) {
                Api = getVisualMark;
            } if (FunType == 5) {
                Api = GetExThickInspPaperMarker;
                dataJson = Data;
            }
            let res = await Api(dataJson);
            if (!res) {
                setTimeout(() => {
                    this.$emit('changeWait', true, true); // 通知上层加载完毕
                }, 500);
                return;
            }
            this.pfdData = [];
            if (res.data.code != 0) {
                setTimeout(() => {
                    this.$emit('changeWait', true); // 通知上层加载完毕
                }, 500);
                return;
            }

            //  部品
            console.log(FunType, 'FunType');
            if (FunType == 1 || FunType == 2 || FunType == 4) {
                if (
                    !res.data.data.visualMarkDetials ||
                    !res.data.data.visualMarkDetials.length
                ) {
                    res.data.data.visualMarkDetials = [];
                }
                try {
                    res.data.data.visualMarkDetials.forEach(item => {
                        item.poS_ORDR_Clone = item.poS_NO
                        item.poS_NO = Number(item.num)
                    })
                    console.log('res.data.data.visualMarkDetials', res.data.data.visualMarkDetials);

                } catch (error) {

                }
                this.pfdData = this.genVisualBallMarkupsList(
                    res.data.data.visualMarkDetials
                );
            }
            if (FunType == 3) {
                // if (!res.data.data || !res.data.data.length) {
                //     res.data.data = [];
                // }
                // try {
                //     res.data.data.forEach(item => {
                //         item.poS_ORDR_Clone = item.poS_ORDR
                //         item.poS_ORDR = Number(item.num)
                //     })
                // } catch (error) {

                // }
                // this.pfdData = this.genThckBallMarkupsList(res.data.data);
                if (!res.data.data || !res.data.data.length) {
                    res.data.data = [];
                }

                this.pfdData = this.genBallMarkupsList(res.data.data);
                console.log('this.pfdData', this.pfdData);
            }
            if (FunType == 5) {
                if (!res.data.data || !res.data.data.length) {
                    res.data.data = [];
                }

                this.pfdData = this.genBallMarkupsList(res.data.data);
                console.log('this.pfdData', this.pfdData);
            }



            // this.pfdData = res.data.data;
            // // 模拟数据

            // this.pfdData = this.genLineGroupAndShow(this.pfdData);
            // 绘制线组
            setTimeout(() => {
                svg_opt.clearAllMarkups();
                if (this.FunType == 1 || FunType == 2 || FunType == 4) {
                    svg_opt.genMarkupOrignDataFromExternalData(this.pfdData);
                } else if (FunType == 3) {
                    svg_opt.genMarkupOrignDataFromExternalData(this.pfdData);
                } else if (FunType == 5) {
                    svg_opt.genMarkupOrignDataFromExternalData(this.pfdData);
                }
                hideLoading();

            }, 500);
            setTimeout(() => {
                this.$emit('changeWait', true); // 通知上层加载完毕
            }, 1500);
        },
        /**
         * 处理线组数据
         */
        genBallMarkupsList(originData) {
            var reList = [];
            for (var i = 0; i < originData.length; i++) {
                let orignItem = originData[i];
                if (orignItem.poS_ORDR == null) continue;

                let temp = {};
                temp.sId = orignItem.poS_ORDR;
                temp.shapeType = Number(orignItem.blN_TYPE) + 12;
                temp.showType = "trans";
                temp.showID = orignItem.poS_ORDR;
                temp.lineColor = "#0000FF";
                temp.lineWidth = "5";
                temp.fontSize = orignItem.blN_FNTSIZ;
                temp.fontName = orignItem.blN_FNTNAM;
                temp.lineStyle = "0";
                temp.points = orignItem.thckBlnPoints;
                temp.IdName = `${orignItem.num}-${orignItem.name}`
                if (temp.points[0].blN_COLOR)
                    temp.ballFillColor = temp.points[0].blN_COLOR;
                else temp.ballFillColor = "#ffffff";
                reList.push(temp);

                for (var j = 0; j < orignItem.thckBlnPoints.length; j++) {
                    orignItem.thckBlnPoints[j].x =
                        orignItem.thckBlnPoints[j].blN_X;
                    orignItem.thckBlnPoints[j].y =
                        orignItem.thckBlnPoints[j].blN_Y;
                }
            }
            return reList;
        },

        genLineGroupAndShow(originData) {
            let lineGroups = [];
            let lastPrl = "";

            console.log(originData);
            console.log(this.isSourcePic);

            // 遍历节点
            for (let i = 0; i < originData.length; i++) {
                let tempData = originData[i];
                let tempLineGroup = null;

                // 如果当前节点与上一个节点的线组号不同，新建线组，压入线组list
                if (lastPrl != tempData.prlNo) {
                    tempLineGroup = {};
                    lineGroups.push(tempLineGroup);

                    tempLineGroup.defaultLineColor = "#0000ff11";
                    tempLineGroup.defaultLineWidth = "10";
                    tempLineGroup.prlNo = tempData.prlNo;
                    tempLineGroup.groupItems = [];
                    tempLineGroup.sId = tempData.prlNo;
                    tempLineGroup.fEntType = "17";
                }

                // 取最近一个线组
                tempLineGroup = lineGroups[lineGroups.length - 1];

                // 如果线组为空 根据当前节点创建
                if (
                    tempLineGroup.groupItems.length == 0 ||
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo != tempData.dtlNo
                ) {
                    let newItem = {};
                    newItem.dtlNo = tempData.dtlNo;
                    newItem.shapeType =
                        tempData.prlType == 1
                            ? "line"
                            : tempData.prlType == 2
                                ? "closeline"
                                : "rect";
                    newItem.fEntType = "17";
                    newItem.text = tempData.title;
                    newItem.points = [];
                    if (this.isSourcePic) {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY,
                        });
                    }
                    tempLineGroup.groupItems.push(newItem);
                } else if (
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo == tempData.dtlNo &&
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].points.length >= 2
                ) {
                    let newItem = {};
                    newItem.dtlNo = tempData.dtlNo;
                    newItem.shapeType =
                        tempData.prlType == 1
                            ? "line"
                            : tempData.prlType == 2
                                ? "closeline"
                                : "rect";
                    newItem.fEntType = "17";
                    newItem.points = [];

                    newItem.points.push(
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points[
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.length - 1
                        ]
                    );

                    if (this.isSourcePic) {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        newItem.points.push({
                            x: tempData.prlX,
                            y: tempData.prlY,
                        });
                    }
                    tempLineGroup.groupItems.push(newItem);
                } else if (
                    tempLineGroup.groupItems[
                        tempLineGroup.groupItems.length - 1
                    ].dtlNo == tempData.dtlNo
                ) {
                    if (this.isSourcePic) {
                        // newItem.points.push({ x: tempData.prlX, y: 0 - Math.abs(tempData.prlY) });
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.push({
                            x: tempData.prlX,
                            y: 0 - Math.abs(tempData.prlY),
                        });
                    } else {
                        // newItem.points.push({ x: tempData.prlX, y: tempData.prlY });
                        tempLineGroup.groupItems[
                            tempLineGroup.groupItems.length - 1
                        ].points.push({ x: tempData.prlX, y: tempData.prlY });
                    }
                }

                lastPrl = tempLineGroup.prlNo;
            }

            // lineGroups[0].groupItems
            console.log(lineGroups)
            return lineGroups;
        },
        genVisualBallMarkupsList(originData) {
            let reList = [];
            for (let i = 0; i < originData.length; i++) {
                let originItem = originData[i];
                let reListLength = reList.length;
                let reListLastItem =
                    reListLength > 0 ? reList[reListLength - 1] : null;

                // 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同
                if (
                    reListLength == 0 ||
                    reListLastItem.pos_no != originItem.poS_NO ||
                    (reListLastItem.pos_no == originItem.poS_NO &&
                        (reListLastItem.bln_kbn != originItem.blN_KBN ||
                            reListLastItem.bln_dtlno != originItem.blN_DTLNO))
                ) {
                    let ballTemp = {};
                    ballTemp.sId = originItem.poS_NO;
                    ballTemp.shapeType = Number(originItem.blN_TYPE) + 12;
                    ballTemp.showType = "trans";
                    ballTemp.showID = originItem.poS_NO;
                    ballTemp.lineColor = "#0000ff";
                    ballTemp.lineWidth = "5";
                    ballTemp.fontSize = originItem.blN_FNTSIZ;
                    ballTemp.fontName = originItem.blN_FNTNAM;
                    ballTemp.lineStyle = "0";
                    ballTemp.points = [];
                    ballTemp.bln_kbn = originItem.blN_KBN;
                    ballTemp.bln_dtlno = originItem.blN_DTLNO;

                    ballTemp.pos_no = originItem.poS_NO;
                    // ballTemp.pos_no1 = originItem.poS_NO;
                    ballTemp.allText = originItem.poS_ORDR_Clone;
                    ballTemp.ballFillColor = "#00000000";

                    ballTemp.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });

                    reList.push(ballTemp);
                } else {
                    reListLastItem.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });
                }
            }
            return reList;
        },
        genThckBallMarkupsList(originData) {
            let reList = [];
            for (let i = 0; i < originData.length; i++) {
                let originItem = originData[i];
                let reListLength = reList.length;
                let reListLastItem =
                    reListLength > 0 ? reList[reListLength - 1] : null;

                // 新建一个球标组 球标数组为空 新位置节点与原球标组pos_no不同
                if (
                    reListLength == 0 ||
                    reListLastItem.pos_no != originItem.poS_ORDR ||
                    (reListLastItem.pos_no == originItem.poS_ORDR &&
                        (reListLastItem.bln_kbn != originItem.blN_KBN ||
                            reListLastItem.bln_dtlno != originItem.blN_DTLNO))
                ) {
                    let ballTemp = {};
                    ballTemp.sId = originItem.poS_ORDR;
                    ballTemp.shapeType = Number(originItem.blN_TYPE) + 12;
                    ballTemp.showType = "trans";
                    ballTemp.showID = originItem.poS_ORDR;
                    ballTemp.lineColor = "#0000ff";
                    ballTemp.lineWidth = "5";
                    ballTemp.fontSize = originItem.blN_FNTSIZ;
                    ballTemp.fontName = originItem.blN_FNTNAM;
                    ballTemp.lineStyle = "0";
                    ballTemp.points = [];
                    ballTemp.bln_kbn = originItem.blN_KBN;
                    ballTemp.bln_dtlno = originItem.blN_DTLNO;

                    ballTemp.pos_no = originItem.poS_ORDR;
                    ballTemp.allText = originItem.poS_ORDR_Clone;
                    ballTemp.ballFillColor = "#00000000";

                    ballTemp.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });

                    reList.push(ballTemp);
                } else {
                    reListLastItem.points.push({
                        bln_x: originItem.blN_X,
                        bln_y: originItem.blN_Y,
                        x: originItem.blN_X,
                        y: originItem.blN_Y,
                    });
                }
            }
            return reList;
        },

        async exportSvgDataStr() {

            if (this.NoData) {
                return ''
            }

            let result = ''
            try {
                result = svg_opt.exportSvgDataStr();
            } catch (error) {

            }
            return result
        },

        // 开始
        initFn() {

            this.getSvgByFunFn();

        }

    },
    created() { },
    mounted() {

    },
    beforeDestroy() {

    },
    destroyed() { },
};
</script>
<style lang="scss" scoped>
.Table {
    height: 100%;
    border-top: 1px solid #e1e1e1;
    padding-top: 12px;
    background-color: #FFF;

    .row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 5px 20px;

        div {
            display: flex;
            align-items: center;

            span {
                margin-right: 12px;
                margin-left: 18px;
            }

            .form-ipt {
                width: 200px;
                height: 24px;

                ::v-deep .el-input__inner {
                    height: 24px;
                    background: #fff;
                }

                ::v-deep .el-input__icon {
                    line-height: 24px;
                }
            }
        }
    }

    .left-draw {
        width: 100%;
        height: 90%;
        cursor: pointer;
        position: relative;

    }
}
</style>